package com.cmes.web;

import com.cmes.core.ResponseCodeData;
import com.cmes.core.context.security.SecurityContextHolder;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 结果增强
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@RestControllerAdvice
public class ResponseCodeDataAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 略过从 Spring 框架提供的 BaseErrorController 返回的错误对象
        if (returnType.getGenericParameterType().getTypeName().startsWith("org.springframework.http.ResponseEntity")) {
            return body;
        }
        if (body == null) {
            return new ResponseCodeData<>().ok().traceId(SecurityContextHolder.getTraceId());
        }
        if (body instanceof ResponseCodeData) {
            ResponseCodeData<?> r = (ResponseCodeData<?>) body;
            if (r.getTraceId() == null) {
                return r.traceId(SecurityContextHolder.getTraceId());
            }
            return body;
        }
        return new ResponseCodeData<>().ok(body).traceId(SecurityContextHolder.getTraceId());
    }

}
